<template>
  <el-drawer
    direction="rtl"
    v-model:visible="isShowDialog"
    @close="handleBtnClick({ type: 'close' })" v-model="isShowDialog" :size="px2vw('842px')">
    <template #header>
      <div class="font-bold pl-[12px]">详情</div>
    </template>

    <div class="pl-[12px]">
      <div class="w-[100%] flex flex-wrap info">
        <div class="w-[50%] flex item h-[45px]"
             v-for="(item,index) in config"
             :key="index"
        >
          <div class="label w-[134px]  bg-[#FAFAFA] h-[100%] flex-center">{{ item.label }}</div>
          <div class="value w-[254px] pl-[25px] flex items-center">{{
              item.type == 'date' ? dayjs(purchaseData[item.code]).format('YYYY-MM-DD HH:mm:ss') : purchaseData[item.code]
            }}

          </div>
        </div>
      </div>


      <div class="mt-[40px]">全部订单信息 >></div>

      <div class="w-[777px] bg-[#FAFAFA] rounded-[8px] mt-[4px] px-[16px] py-[16px]">
        <el-tabs v-model="activeTab" class="demo-tabs" @tab-click="handleBtnClick">
          <el-tab-pane :label="item.name" :name="item.code"
                       v-for="(item,index) in tabs"
                       :key="index"
          >

            <QueryTable
              v-if="item.code == 'info'"
              :list="purchaseData.purchaseOrderDetailRespVOList || []"
              :total="0"
              @execute="handleBtnClick"
              :thead="thInfo"
              v-model="queryParams"
              :show-action="false"
              :show-section="false"
              :show-expand="false"
              pk="id"
            >
              <template #name="{row}">
                <div class="flex">
                  <ImagePreview :src="row.cover" :width="38" :height="38"/>
                  <div class="ml-[10px]">
                    <div class="text-[#3721FF]" style="text-align: left">{{ row.productName }}</div>
                    <div class="mt-[3px] text-[#999999]">ID:{{ row.productId }}</div>
                  </div>
                </div>

              </template>
            </QueryTable>

            <QueryTable
              v-if="item.code == 'record'"
              :list="purchaseData.purchaseOrderDetailRespVOList || []"
              :total="total"
              @execute="handleBtnClick"
              :thead="thRecord"
              v-model="queryParams"
              :show-action="true"
              :show-section="false"
              :show-expand="false"
              :btns="tableBtnList"
              pk="id"
            >
              <template #btn="scope">

                <div

                >

                  <div class="flex-center" v-style="`gap:10px`"
                       v-if="!scope.row.state"
                  >
                    <div>
                             <span v-for="(item, index) in tableBtnList" :key="index"
                                   v-style="`gap:10px`">
                <span
                  class="cursor-pointer"
                  :style="`color:${item.color}`"
                  @click="
                    handleBtnClick({
                          type:item.code,
                      data:scope.row
                    })
                  "
                >
                  {{ item.name }}
                </span>

                <span v-style="`color:#e7e7e7;margin-left:10px`"
                      v-if="index !== tableBtnList.length - 1">|</span>
              </span>
                    </div>

                  </div>
                </div>

              </template>

              <template #productName="{row}">
                <div>
                  <div class="flex items-center">
                    <ImagePreview :src="row.cover" width="50px"/>
                    <div class="ml-[10px] w-[100px]" style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" :title="row.productName">{{ row.productName }}</div>
                  </div>
                </div>

              </template>

              <template #warehouseEntryTime="{row}">
                <div>
                  <div v-if="row.state">
                    {{  dayjs(row.warehouseEntryTime).format('YYYY-MM-DD HH:mm:ss')   }}
                  </div>
                </div>
              </template>
            </QueryTable>

            <QueryTable
              v-if="item.code == 'link'"
              :list="purchaseLinkList"
              :total="0"
              @execute="handleBtnClick"
              :thead="thLink"
              v-model="queryParams"
              :show-action="false"
              :show-section="false"
              :show-expand="true"
              pk="id"
              :expandKeys="purchaseLinkList.map(item=>item.id)"
            >
              <template #name="{row}">
                <div class="flex">
                  <ImagePreview :src="row.cover" :width="38" :height="38"/>
                  <div class="ml-[10px]">
                    <div class="text-[#3721FF] w-[100px]" style="text-align: left;overflow: hidden;text-overflow: ellipsis;">{{ row.productName }}</div>
                    <div class="mt-[3px] text-[#999999]">ID:{{ row.productId }}</div>
                  </div>
                </div>
              </template>

              <template #creator>
                <div>{{ purchaseData.purchaseName }}</div>
              </template>

              <template #department>
                <div>{{ purchaseData.productDeptName }}</div>
              </template>

              <template #expand="{row}">
                <div class="pl-[100px]">
                  <div v-for="(item,index) in computePurchaseLinkList(row)" :key="index"
                       class="flex items-centerx" :class="index == 0 ? '' : 'mt-[15px]'">
                    <div class="mr-[35px] flex">
                      <div>采购链接：</div>
                      <a class="w-[400px] text-[#3721FF]"
                           style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap;"
                        :href="item.url " target="_blank"
                      >
                        {{ item.url }}
                      </a>
                    </div>

                    <div>备注：{{ item.remark }}</div>
                  </div>
                </div>
              </template>
            </QueryTable>

          </el-tab-pane>

        </el-tabs>

      </div>
    </div>


    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleBtnClick({ type: 'close' })">取 消</el-button>

        <el-button type="primary" @click="handleBtnClick({ type: 'inventoryAll' })">一键入库
        </el-button>

      </div>
    </template>

  </el-drawer>
</template>
<script setup lang="ts">
import dayjs from "dayjs";
import {px2vw, throttle} from "@/utils";
import QueryTable from "@/components/TableData/index.vue"
import Icon from "@/components/Icon/src/Icon.vue";
import ImagePreview from "@/components/ImagePreview/index.vue"
import {confirmPromote} from "@/utils";
import {useMessage} from "@/hooks/web/useMessage";

import {PurchaseOrderApi, PurchaseOrderVO} from "@/api/purchase/order";


const props = defineProps({
  modelValue: {
    type: Boolean,
    required: false,
    default: () => false
  },
  info: {
    type: Object,
    required: false,
    default: () => {
    }
  }
})

const emit = defineEmits(['update:modelValue', 'confirm']);

const isShowDialog = ref(false);

const purchaseData = ref<PurchaseOrderVO>({})

const queryParams = ref({
  pageNo: 1, pageSize: 10
})


const tableBtnList = ref([
  {
    color: '#3721FF',
    code: 'inventoryIn',
    name: '确认入库'
  }
]);


const config = ref([
  {
    label: "采购订单",
    code: "id"
  },
  {
    label: "入库仓库",
    code: "storeName"
  },
  {
    label: "供应商名称",
    code: "supplier"
  },
  {
    label: "物流单号",
    code: ""
  },
  {
    label: "采购渠道",
    code: "purchasingChannels"
  },
  {
    label: "渠道订单号",
    code: "channelOrder"
  },
  {
    label: "采购员",
    code: "purchaseName"
  },
  {
    label: "采购金额",
    code: "totalPurchaseAmount"
  },
  {
    label: "采购时间",
    code: "purchaseDate",
    type: 'date'
  },
  {
    label: "线上订单号",
    code: "onlineOrder"
  },
  {
    label: "采购链接",
    code: "link"
  },
  {
    label: "备注",
    code: "remark"
  }
])

const tabs = ref([
  {
    name: "商品信息",
    code: "info"
  },
  {
    name: "入库记录",
    code: "record"
  },
  {
    name: "采购链接",
    code: "link"
  }
])
const activeTab = ref(tabs.value[0].code);

const total = ref(0)
const thInfo = ref([
  {
    name: '商品名称/ID',
    code: 'name',
    type: 'numberRanger',
    search: true,
    width: "200px"
  },
  {
    name: 'sku',
    code: 'sku',
    type: 'numberRanger',
    search: true
  },
  {
    name: '属性',
    code: 'property',
    type: 'numberRanger',
    search: true
  },
  {
    name: '采购单价（￥）',
    code: 'purchaseAmount',
    type: 'numberRanger',
    search: true
  },
  {
    name: '采购数量（件）',
    code: 'purchaseNumber',
    type: 'numberRanger',
    search: true
  },
])

const thRecord = ref([

  {
    name: '商品名称',
    code: 'productName',
    type: 'numberRanger',
    search: true,
    width:"200px"
  },
  {
    name: 'sku',
    code: 'sku',
    type: 'numberRanger',
    search: true
  },
  {
    name: '属性',
    code: 'property',
    type: 'numberRanger',
    search: true,
    width: "200px"
  },


  {
    name: '入库数量',
    code: 'purchaseNumber',
    type: 'numberRanger',
    search: true
  },

  {
    name: '入库时间',
    code: 'warehouseEntryTime',
    type: 'numberRanger',
    date: true
  },
  {
    name: '操作者',
    code: 'auditName',
    type: 'numberRanger',
    search: true
  },
])

const thLink = ref([
  {
    name: '商品名称',
    code: 'name',
    type: 'numberRanger',
    search: true,
    width: "200px"
  },
  {
    name: '创建部门',
    code: 'deptName',
    type: 'numberRanger',
    search: true
  },

  {
    name: '创建者',
    code: 'creator',
    type: 'numberRanger',
    search: true
  },

])

const purchaseLinkList = ref([])

const computePurchaseLinkList = (row) => {

  return row.purchaseList || []
}


const handleBtnClick = (e) => {
  let type = e.type;
  try {
    fn[type](e)
  } catch (e) {
    console.log(`${type}不存在`)
  }

}

const fn = {
  inventoryAll() {
    let list = purchaseData.value.purchaseOrderDetailRespVOList || [];
    let ids = list.filter(item=>!item.state).map(item => {
      return item.sku
    })?.join(",")
    handleInventoryIn(ids);
  },
  inventoryIn: async (e) => {
    console.log(e,"eee")
    handleInventoryIn(e.data.sku);
  },
  add({index}) {
    dataList.value[index].list.push({
      link: "",
      remark: "",
      isEdit: true
    })
  },
  async delItem({index, idx}) {
    await confirmPromote({
      content: "是否删除该采购链接？"
    })
    dataList.value[index].list.splice(idx, 1);
  },
  close() {

    emit('update:modelValue', false)
  },
  confirm() {
    fn.close();
    emit('confirm', {
      type: 'purchaseConfirm', data: {
        dataList: dataList.value,
        info: props.info
      }
    })
  },

}

const handleInventoryIn =async (skus) => {
  await confirmPromote({
    content: "确认入库吗"
  })

  let res = await PurchaseOrderApi.inventoryIn({
    sku: skus,
    purchaseOrderId: props.info.id + ''
  })
  getDetail();
  useMessage().success("入库成功")
}

const getDetail = async () => {
  let res = await PurchaseOrderApi.getPurchaseOrder(props.info.id);
  let obj =  res || {}
  purchaseData.value ={
    ...obj,
    link:props.info.link
  }

  //获取采购链接
  getPurchaseLink();
}

const getPurchaseLink = async () => {
  //获取产品
  let res = await PurchaseOrderApi.getPurchaseLink({
    productIds:purchaseData.value.purchaseOrderDetailRespVOList.map(item => {
      return item.productId
    }).join(','),
    purchaseOrderId:props.info.id
  });

  let list =  res || [];
  let arr = [];
  list.forEach(item=>{
    let isIn = arr.find(at=>{
      return at.productId == item.productId
    })

    if(!isIn){
      arr.push(item)
    }
  })


  purchaseLinkList.value =arr

}


watch(() => props.modelValue, () => {
  isShowDialog.value = props.modelValue;
  if (props.modelValue) {
    //查询采购订单详情
    getDetail();

  }
})

</script>
<style lang="scss" scoped>
.info {
  border: solid 1px #F3F3F3;
  border-radius: 8px;
  overflow: hidden;

  .item {
    border-bottom: solid 1px #F3F3F3;
    border-right: solid 1px #F3F3F3;

    &:nth-last-of-type(1), &:nth-last-of-type(2) {
      border-bottom: solid 0px #F3F3F3;
    }

    &:nth-of-type(2n) {
      border-right: solid 0px #F3F3F3;
    }


  }
}
</style>
